<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
        <TableHeader
            :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch',  'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('chat.shopChat.quick Search Fields') })"
        >

            <el-button type="warning" @click="chat_show_act(0)">联系商家</el-button>

        </TableHeader>

        <!-- 表格 -->
        <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
        <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
        <Table ref="tableRef"></Table>

        <!-- 表单 -->
        <PopupForm />

        <el-dialog
            v-model="chat_show"
            title="留言板"
            width="500"
            :draggable="true"

        >

            <div class="chat-container">
                <!-- 消息列表 -->
                <div class="message-list" ref="messageList">
                    <div
                        v-for="(message, index) in messages"
                        :key="index"

                    >
                        <p  :class="[ message.type == 1 ? 'user-message1' : 'bot-message1']" >{{message.nickname}} {{message.create_time_text}}</p>
                        <div class="message-content" :class="['message', message.type == 1 ? 'user-message' : 'bot-message']">
                            {{ message.content }}
                        </div>

                    </div>
                </div>

                <!-- 输入框 -->
                <div class="input-container">
                    <input
                        v-model="newMessage"
                        type="text"
                        placeholder="请输入消息内容"
                        @keyup.enter="sendMessage"
                    />
                    <button @click="sendMessage">发送</button>
                </div>
            </div>
        </el-dialog>

        <el-dialog
            v-model="chat_show_create"
            title="联系商家"
            width="500"
        >


            <FormItem label="商家" type="remoteSelect" v-model="baTable.form.items!.shop_id" prop="shop_id" :input-attr="{ pk: 'xxz_shop.id', field: 'name', 'remote-url': '/admin/Shop/index' }" placeholder="请选择一个商家" />

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="chat_show_create = false">取消</el-button>
                    <el-button type="primary" @click="chat_create">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script setup lang="ts">
import { onMounted, provide, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import FormItem from "/@/components/formItem/index.vue";
import createAxios from "/@/utils/axios";
import {ElMessage} from "element-plus";
import {useAdminInfo} from "/@/stores/adminInfo";
import moment from "moment"
defineOptions({
    name: 'chat/shopChat',
})

const { t } = useI18n()
const tableRef = ref()
const optButtons: OptButton[] = defaultOptButtons(['edit', 'delete'])


optButtons.push(
    {
        render: 'tipButton',
        // name 是任意的
        name: 'info',
        // title 是语言翻译 key
        title: '留言板',
        text: '',
        // type: 'warning',
        // icon: 'fa fa-search-plus icon',
        type: 'success',
        icon: 'el-icon-ChatDotSquare',
        click(row, field) {
            chat_show_act(row.id);
        },
        display(row, field) {
            if (row.admin_unread  <= 0){
                return true;
            }else{
                return false;
            }
        },

    },
    {
        render: 'tipButton',
        // name 是任意的
        name: 'info',
        // title 是语言翻译 key
        title: '留言板',
        text: '',
        // type: 'warning',
        // icon: 'fa fa-search-plus icon',
        type: 'primary',
        icon: 'el-icon-ChatDotSquare',
        click(row, field) {
            chat_show_act(row.id);
        },
        display(row, field) {
            if (row.admin_unread  > 0){
                return true;
            }else{
                return false;
            }
        },

    },
)

/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/chat.shopChat/'),
    {
        pk: 'id',
        column: [
            { type: 'selection', align: 'center', operator: false },
            { label: t('chat.shopChat.id'), prop: 'id', align: 'center', width: 150, operator: 'RANGE', sortable: false },
            { label: t('chat.shopChat.shop_id'), prop: 'shop_id', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE' },
            { label: t('chat.shopChat.shop__name'), prop: 'shop.name', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE' },
            { label: t('chat.shopChat.shop__phone'), prop: 'shop.phone', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE' },
            // { label: t('chat.shopChat.shop_unread'), prop: 'shop_unread', align: 'center', operator: 'RANGE', sortable: false },
            // { label: t('chat.shopChat.admin_unread'), prop: 'admin_unread', align: 'center', operator:false, sortable: 'custom' },
            // { label: t('chat.shopChat.create_time'), prop: 'create_time', align: 'center', render: 'datetime', operator: 'RANGE', sortable: 'custom', width: 160, timeFormat: 'yyyy-mm-dd hh:MM:ss' },
            { label: t('chat.shopChat.update_time'), prop: 'update_time', align: 'center', render: 'datetime', operator: 'RANGE', sortable: true, width: 160, timeFormat: 'yyyy-mm-dd hh:MM:ss' },
            { label: t('Operate'), align: 'center', width: 100, render: 'buttons', buttons: optButtons, operator: false },
        ],
        dblClickNotEditColumn: ['all'],
        defaultOrder: { prop: 'update_time', order: 'desc' },
    },
    {
        defaultItems: { shop_unread: 0, admin_unread: 0 },
    }
)

provide('baTable', baTable)

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})

const chat_show = ref(false)
const chat_show_create = ref(false)

const messages = ref([

]);
const newMessage = ref("");
const shop_chat_id = ref(0);
const sendMessage = () => {
    if (newMessage.value.trim() !== "") {
        const create_msg_data = ref({})
        create_msg_data.value = {shop_chat_id:shop_chat_id.value,type: "1", create_time_text: moment().format('YYYY-MM-DD HH:mm:ss'), nickname: useAdminInfo().nickname, content: newMessage.value }
        messages.value.push(create_msg_data.value);
        newMessage.value = "";

        setTimeout(function () {
            scrollToBottom();
        })

        // 提交保存
        createAxios({
            url: '/admin/chat.ShopChatLog/add_log_ajax',
            method: 'post',
            data: create_msg_data.value
        },{
            loading:false
        },{
            text: ''
        })
            .then((res) => {
                if (res.code == 1){
                }else {
                    ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
            .catch((resx) => {
            })

    }
};

const messageList = ref("messageList");
const scrollToBottom = () => {
    messageList.value.scrollTop = messageList.value.scrollHeight;
};


const chat_show_act = (id) => {


    if (id > 0){
        shop_chat_id.value = id;
        createAxios({
            url: '/admin/chat.ShopChatLog/index_ajax',
            method: 'post',
            data: {id:id}
        },{
            loading:true
        },{
            text: '获取留言记录...'
        })
            .then((res) => {
                if (res.code == 1){
                    messages.value = res.data;
                    chat_show.value = true;
                    setTimeout(function () {
                        scrollToBottom();
                    })

                }else {
                    ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
            .catch((resx) => {
            })
    }else {

        chat_show_create.value = true;
    }

}

// 指定一个商家联系
const chat_create = () => {

    createAxios({
        url: '/admin/chat.ShopChatLog/add_ajax',
        method: 'post',
        data: {shop_id:baTable.form.items!.shop_id}
    },{
        loading:true
    },{
        text: '留言板创建中...'
    })
        .then((res) => {
            if (res.code == 1){
                chat_show_create.value = false;
                chat_show_act(res.data.id);


            }else {
                ElMessage({
                    message: res.msg,
                    type: 'error',
                })
            }
        })
        .catch((resx) => {
        })
}

</script>

<style scoped lang="scss">
.chat-container {
    width: 100%;
    max-width: 500px;
    height: 550px;
    border: 1px solid #ccc;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    overflow: hidden;
}

.message-list {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
    background-color: #f9f9f9;
}

.message {
    margin-bottom: 10px;
    padding: 5px 10px;
    border-radius: 5px;
    max-width: 70%;
    word-wrap: break-word;
}

.user-message {
    background-color: #00a6ff;
    color: white;
    align-self: flex-end;
    margin-left: 150px;
}

.user-message1 {
    text-align: right;

}

.bot-message {
    background-color: #e5e4e4;
    color: black;
    align-self: flex-start;
}

.input-container {
    display: flex;
    padding: 10px;
    border-top: 1px solid #ccc;
}

.input-container input {
    flex: 1;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin-right: 10px;
}

.input-container button {
    padding: 10px 20px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

.input-container button:hover {
    background-color: #0056b3;
}
</style>
